<?php
/**
 * 用户下单
 */
namespace Home\Controller;


use Common\Library\CacheRedis;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Common\Library\SendSMS;
use Common\Vendor\Hook\BaseHook;
use Home\Model\ConsumeHistoryModel;
use Home\Model\CreditVettingModel;
use Home\Model\CustomerAuthModel;
use Think\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log;
use Think\Cache\Driver\Redis;

class WithdrawalsOrderController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        try {
            Request::parse();
        } catch (BusinessException $e) {
            $this->ajaxReturn(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
        }
    }

    /*** 保存用户当前位置信息 ***/
    private function saveLocationHistory()
    {
        $locationModel = D("CustomerLocationHistory");
        $locationData = [
            'customer_id' => I('post.customer_id', 0, 'intval'),
            'province' => I("post.province", ''),
            'city' => I("post.city", ''),
            'country' => I("post.country", ''),
            'address' => I("post.address", ''),
            'location' => I("post.location", ''),
            'add_time' => time()
        ];
        Log::write("Customer location:" . json_encode($locationData, JSON_UNESCAPED_UNICODE), Log::INFO);
        $locationModel->add($locationData);
    }

    /*** 公共参数校验 ***/
    public function orderCommonCheck($data, $checkPass = true)
    {
        Log::write("[".ACTION_NAME."][orderCommonCheck][customer_id=".$data['customer_id']."]:start", Log::INFO);
        $customer_id = I('post.customer_id', 0, 'intval');
        $province = I("post.province", '', 'string');
        $city = I("post.city", '', 'string');
        $country = I("post.country", '', 'string');
        $location = I("post.location", '', 'string');
        $address = I("post.address", '', 'string');
        $password = I("post.pay_pass", '', 'string');
        $apply_amount = I("post.apply_amount", 0, 'intval') ? I("post.apply_amount", 0, 'intval') : $data['amount'];

	if(!$customer_id || /*!$country || !$location ||*/ !$apply_amount) {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }

        //用户有效性校验
        $customer = M('Customer')->where(['id' =>$customer_id])->find();
        if(!$customer){
            BusinessException::throwException(Constant::CUSTOMER_NOT_FOUND);
        }

        //支付密码正确性校验
        if($checkPass){
            /* 0. 密码参数校验 */
            if(!$password){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            /* 1. 未设置密码提示 */
            if (!$customer['pay_pass']) {
                BusinessException::throwException(Constant::UNSET_PAY_PASS);
            }
            /* 2.密码不正确提示 */
            if (password_unmatched($password, $customer['pay_pass'])) {
                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
            }
        }

        //校验用户当前是否为逾期未还款或待审核，是则不允许下单
        $chk = D('ConsumeHistory')->chkWithdFineOrWaitReview($customer_id);
        if($chk){
            BusinessException::throwException(Constant::NOT_ALLOW_APPLY);
        }

        Log::write("[orderCommonCheck]:return=>".json_encode($customer, JSON_UNESCAPED_UNICODE), Log::INFO);
        Log::write("[".ACTION_NAME."][orderCommonCheck]:end\n", Log::INFO);

        return $customer;
    }

    /*** 提现申请 ***/
    public function withdrawalsApply()
    {
        try {
            //0.参数校验
            $data = I('post.');
            //TODO 这个地方暂时不能用，需要后续加上
            //$customer = $this->orderCommonCheck($data, true);

            $customer_id = I('post.customer_id', 0, 'int');

            $customer = M('Customer')->where(['id' =>$customer_id])->find();
            /***|打开支付密码校验|***/
            //验证支付密码
//            if (!$customer['pay_pass']) {
//                Log::pay_write('+++++++++payConfirm未设置支付密码+++++++++');
//                BusinessException::throwException(Constant::UNSET_PAY_PASS);
//            }
//            if (password_unmatched($data['pay_pass'], $customer['pay_pass'])) {
//                Log::pay_write('+++++++++payConfirm支付密码校验失败+++++++++');
//                BusinessException::throwException(Constant::PAY_PASS_UNMATCHED);
//            }
            //Log::pay_write('+++++++++payConfirm支付密码校验成功+++++++++');
            /***|打开支付密码校验|***/
            if ($data['repay_id'] == 4){
                $redis = new Redis();
                $k = "七天产品的用户数量".date("Y-m-d", time());
                $max_num = M('SysInstallmentPlan')->where(['id'=>4])->find();
                $num = $redis->get($k);
                Log::write("^^^^^^^^^^^^用户数量".$num."用户标识".$customer['id']);
                if ($num > $max_num['max_num']){
                    BusinessException::throwException("今天7天产品的数量用完了，请更换产品类型");
                } else {
                    $redis->set($k,($redis->get($k)+1));
                }
            }
            //找到该用户的最后一条记录，如果不是已还款完成的，则提示他如下信息
            $cond3 = [
                'customer_id'=>$data['customer_id']
            ];
            $res = D('ConsumeHistory')->where($cond3)->order('add_time desc')->limit(1)->find();
            //找到并且是非还款完成态
            if(!empty($res) && !($res['type'] == Constant::PAY_TYPE_WITHDRAWAL && $res['status'] == ConsumeHistoryModel::STATUS_PAY_OK)){
                //错误提示
                $t = $res['type'];
                $s = $res['status'];
                Log::write("用户提现的状态", "customer_id:".$data['customer_id']."; type : ".$t."; status : ".$s, Log::INFO);
                if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && ($s == ConsumeHistoryModel::STATUS_WAIT_REVIEWED || $s == ConsumeHistoryModel::STATUS_WAIT_REVIEWEDS || $s == ConsumeHistoryModel::STATUS_WAIT_REVIEWEDSS)){
                    $this->ajaxReturn(['code' => 100, 'msg' => "亲，您的订单处于待审核状态，不可再次申请哦~~"]);
                }

                else if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && $s == ConsumeHistoryModel::STATUS_TONDDUN_FAILED){
                    $this->ajaxReturn(['code' => 100, 'msg' => "亲，您的账户在黑名单中，不可再次申请哦~~"]);
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL && $s == ConsumeHistoryModel::STATUS_REVIEWED){
                    $this->ajaxReturn(['code' => 100, 'msg' => "亲，您有一笔订单未还款，还款以后再次申请哦~~"]);
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && $s == ConsumeHistoryModel::STATUS_REVIEW_FAILED){
                    $now = time();
                    $diff = ($now - $res['add_time']);
                    if($diff < 30 * 24 * 3600) {
                        $this->ajaxReturn(['code' => 100, 'msg' => "亲，您的订单申请未通过，请于30个自然日后再次申请~~"]);
                    }
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && $s == ConsumeHistoryModel::STATUS_JUJUE){
                    $now = time();
                    $diff = ($now - $res['add_time']);
                    if($diff < 30 * 24 * 3600) {
                        $this->ajaxReturn(['code' => 100, 'msg' => "亲，您上笔订单没有及时提现，被自动拒绝，请于30个自然日后再次申请~~"]);
                    }
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL && $s == ConsumeHistoryModel::STATUS_WAITING_REPAY){
                    $this->ajaxReturn(['code' => 100, 'msg' => "亲，您的订单处于待打款状态~~"]);
                }
                else{
                    $this->ajaxReturn(['code' => 100, 'msg' => "抱歉，系统错误，请邮件联系管理员!~~"]);
                }
            }
            //保存位置信息
            $this->saveLocationHistory();
            $county_id = D('Position')->getCountyIDByCountyName($data['province'], $data['country']);

            //录入数据，等待审核
            $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED; //设置审核状态
            $customer['consume_amount'] = $data['apply_amount'];

            //生成零元还款消费记录
            $consumeData = [
                'amount' => $data['apply_amount'],
                'consume_amount' => $data['apply_amount'],
                'discount_first_order' => 0,
                'discount_full_amount' => 0,
                'discount_full_reduce' => 0,
                'type' => Constant::PAY_TYPE_WITHDRAWAL_APPLY,
                'customer_id' => $data['customer_id'],
                'repay_id' => isset($data['repay_id']) ? $data['repay_id'] : 0,
                'merchant_id' => 0,
                'status'=>$status,
                'repayment_time' => 0,
                'add_time' => time(),
                'county_id' => $county_id
            ];

            $insertId = D('ConsumeHistory')->add($consumeData);
            /********************等待审核入库完成，将consume_id入CustomerCome表************************/
            Log::borrow_write("CustomerCome-----------------------------------------------------start");
            Log::borrow_write("CustomerCome---接收application_name". I('post.application_name') ."-----|device_type". I('post.device_type') ."---------------------------------------------start");
            //暂不用微服务，注释微服务
            // $func = "getCustomerComeFind";
            // $xml_data = [
            //     'where' => [
            //         'customer_id' => I('post.customer_id'),
            //         'consume_id'  => 0
            //     ],
            //     'field' =>  'customer_id,channel_id,add_time,consume_id'
            // ];
            // $CustomerComeFind = D('Query')->queryUserCenterPost($func, $xml_data);
            $CustomerComeFind = M('customer_come', null)->where("customer_id = '$customer_id' and consume_id = '0'")->find();
            Log::borrow_write("*******CustomerCome查询结果|". json_encode($CustomerComeFind) ."|*******：");
            // Log::borrow_write("*******CustomerCome查询结果|". $CustomerComeFind .'|queryUserCenterPost数据传参：func|'. $func . '|xml_data|' . json_encode($xml_data) ."|*******：");
            if (isset($CustomerComeFind) && !empty($CustomerComeFind)) {
                //若已注册，则重新组装数据添加订单记录
                // $CustomerComeFind = json_decode($CustomerComeFind, true);
                $customer_come_data = $CustomerComeFind;
                $customer_come_data['application_name'] = I('post.application_name');
                $customer_come_data['device_type'] = I('post.device_type');
                $customer_come_data['add_time'] = date('Y-m-d H:i:s',time());
                $customer_come_data['consume_id'] = $insertId;
                unset($customer_come_data['id']);
                $customerAddRes = M('customer_come', null)->add($customer_come_data);
                Log::borrow_write("*******CustomerCome表入库结果|". $customerAddRes .'|非零则成功|customer_come_data数据传参：'. json_encode($customer_come_data) ."|*******：");
            }
            Log::borrow_write("CustomerCome-----------------------------------------------------end");
            /********************等待审核入库完成，将consume_id入CustomerCome表************************/
            /********************等待审核入库完成，调用server3rd服务器接口服务************************/
            // $url = 'http://server3d.huoyanzichan.com/Home/Zm/getRiskDecision';
            // $url = 'http://server3rd.huoyanzichan.com/Home/Zm/getRiskDecision';//我方的正式服
            // $url = Constant::SERVER_THIRD_TEST_URL . '/Home/Zm/getRiskDecision';
            $url = Constant::SERVER_THIRD_URL . '/Home/Zm/getRiskDecision';//我方的正式服
            $xml_data = [
                'eventType' => 'loan',
                'customer_id' => I('post.customer_id'),//'366407'
                // 'tokenKey' => '201509141504865096454',//I('post.tokenKey')1474e2ab-76cf-430a-8d79-ce3715f92e2e
                'tokenKey' => I('post.tokenKey'),//
            ];
            $server3rdResponse = D('Server3rd')->server3rd_post($url,$xml_data);
            Log::borrow_write("*+++++白骑士风险决策API||请求地址：".$url.'|数据传参：'.json_encode($xml_data)."|返回结果：".json_encode($server3rdResponse)."|*******：");
            /******************************************************************************************/
            $url = Constant::SERVER_THIRD_TEST_URL . '/Home/Zm/getDeviceMsgQuery';
            // $url = Constant::SERVER_THIRD_URL . '/Home/Zm/getDeviceMsgQuery';//我方的正式服
            $xml_data = [
                'platform' => I('post.platform'),
                'customer_id' => I('post.customer_id'),//'366407'
                'consume_id' => $insertId,//'366407'
                // 'tokenKey' => '201509141504865096454',//I('post.tokenKey')1474e2ab-76cf-430a-8d79-ce3715f92e2e
                'tokenKey' => I('post.tokenKey'),//
            ];
            $server3rdResponse = D('Server3rd')->server3rd_post($url,$xml_data);
            Log::borrow_write("*+++++白骑士设备信息查询API||请求地址：".$url.'|数据传参：'.json_encode($xml_data)."|返回结果：".json_encode($server3rdResponse)."|*******：");
            /*********************等待审核入库完成，调用server3rd服务器接口服务************************/
            if (!$insertId) {
                
                BusinessException::throwException(Constant::FAILED);
            }
            //记录信审表
            $creditVetting = [
                'customer_id' => $data['customer_id'],
                'consume_id' => $insertId,
                'credit_amount' => 0,
                'status' => CreditVettingModel::STATUS_WAITING_REVIEW,
                'type' => Constant::PAY_TYPE_WITHDRAWAL_APPLY
            ];
            $ins = M('CreditVetting')->add($creditVetting);
            Log::write("[".ACTION_NAME."][记录信审信息][customer_id=".$data['customer_id']."]:".json_encode($creditVetting).",result:".$ins, Log::INFO);

            //同步最新的同盾设备id值
            $new_data_customer = [];
            $push_id = I('post.push_id', '', 'string');
            $tdId = I('post.black_box', '', 'string');
            if(!$tdId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            if((0 == strlen($data['customer']['tongdun_device_id']) || $tdId != $data['customer']['tongdun_device_id']) && $tdId != 'h5'){
                $new_data_customer['tongdun_device_id'] = $tdId;
            }
            if($push_id && $push_id != 'h5'){
                $new_data_customer['push_id'] = $push_id;
            }
            if($new_data_customer){
                if(false === M('Customer')->where(['id' => $data['customer_id']])->setField($new_data_customer)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }
                $customer['tongdun_device_id'] = $tdId;
            }

            //稽审
            if($this->AuditOrder($customer)){
                $ids = array('consume_id'=>$insertId, 'credit_id'=>$ins, 'customer_id'=>$data['customer_id']);
                if(!$this->AuditFinish($ids)){
                    BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                }

                $res2App['is_need_verify'] = 0;
                $res2App['amount'] = Constant::WITHDRAWALS_DEFAULT_AMOUNT;
            }else{
                //执行决策
//                $customer['consume_id'] = $insertId;
//                $ret = BaseHook::executeHook("MONEY_DECISION_ENGINE_HOOK", $customer, Constant::TONGDUN_CASH_APPLY);
//                Log::write("决策引擎:" . json_encode($ret), Log::INFO);
//                if (Constant::SUCCESS != $ret['code']) {
//                    if(false === D('ConsumeHistory')->where(['id' => $insertId])->setField('status', ConsumeHistoryModel::STATUS_TONDDUN_FAILED)){
//                        //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
//                        return ['code'=>'201','msg'=>Constant::INTERNAL_ERROR_MYSQL];
//                    }
//                    $save_data = ['status'=>CreditVettingModel::STATUS_AUTO_REFUSE, 'reason'=>$ret['msg']];
//                    if(false === D('CreditVetting')->where(['id'=>$ins])->setField($save_data)){
//                        //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
//                        return ['code'=>'201','msg'=>Constant::INTERNAL_ERROR_MYSQL];
//                    }
//                    //BusinessException::throwException($ret['code'], $ret['msg']);
//                    return ['code'=>'201','msg'=>$ret['msg']];
//                }
                $redis = new Redis();
                $key='该用户需要重新认证-'.$customer_id;
                $key2 = '该用户弹窗时间'.$customer_id;
                $cust = M('Customer')->where(['id'=>$customer_id])->find();
                if ($cust['accreditation'] == 1 || $redis->get($key)){
                    Log::borrow_write("*******withdrawalsApply|".$customer_id."需要重新认证|*******：");
                    if($cust['accreditation'] ==1){
                        $data1 = [
                            'accreditation'=>0,
                            'accreditation_status'=>0
                        ] ;
                        Log::borrow_write("*******withdrawalsApply|".$customer_id."accreditation|字段清零*******：");
                        M('Customer')->where(['id'=>$customer_id])->save($data1);
                    }
                    //需要重新拉取通讯录等信息
                    $res2App['tel_refresh'] = 1;
                    Log::borrow_write("*******withdrawalsApply|".$customer_id."accreditation|tel_refresh字段为1*******：");
                } else {
                    Log::borrow_write("*******withdrawalsApply|".$customer_id."accreditation|tel_refresh字段为0*******：");
                    $res2App['tel_refresh'] = 0;
                }
                //查询用户订单信息
                /*$fconsume = M('ConsumeHistory')->where(['customer_id'=>$customer_id,'status'=>3])->order('add_time desc')->limit(1)->find();
                $paylog = M('CustomerBillPayLog')->where(['consume_id'=>$fconsume['id']])->find();
                $consumehistory = M('ConsumeInstallmentHistory')->where(['parent_id'=>$fconsume['id']])->find();
                if (($paylog['amount'] != $consumehistory['amount']) || $redis->get($key)){
                    //需要重新拉取通讯录等信息
                    $res2App['tel_refresh'] = 1;
                } else {
                    $res2App['tel_refresh'] = 0;
                }*/
                $redis->rm($key);
                $redis->rm($key2);
                Log::borrow_write("*******withdrawalsApply|".$customer_id."删除redi ske".$key.$key2."y*******：");
                $res2App['is_need_verify'] = 1;
                $res2App['consume_id'] = $insertId;
            }
            //$ret = Constant::getReturn(Constant::SUCCESS);
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res2App;
            //提示文字
            $ret['data']['tip'] = "";//九月30号改成相应的文字|XXXX10.1期间审核较慢，请您在10.9号关注审核结果。
            // Log::borrow_write("待审核用户".$customer_id."时间".time());
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
            //return ['code'=>'201','msg'=>$e->getMessage()];
        }
        Response::format($ret);
        //BusinessException::throwException("10.1期间审核较慢，请您在10.9号关注审核结果。");
        $this->ajaxReturn($ret);
    }
    /*** 融360客户|提现申请
     *['customer_id'=>''];
     *['province'=>''];
     *['country'=>''];
     *['apply_amount'=>''];
     *['repay_id'=>''];
     *['push_id'=>''];
     *['black_box'=>''];
     *['customer']['tongdun_device_id']='';
     *
     ***/
    public function withdrawalsRongApply($data)
    {
        try {
            //0.参数校验
            //TODO 这个地方暂时不能用，需要后续加上
            //$customer = $this->orderCommonCheck($data, true);
            //$customer_id = $data['customer_id'];
            $customer = M('Customer')->where(['id' =>$data['customer_id']])->find();
            //找到该用户的最后一条记录，如果不是已还款完成的，则提示他如下信息
            $cond3 = [
                'customer_id'=>$data['customer_id']
            ];
            $res = D('ConsumeHistory')->where($cond3)->order('add_time desc')->limit(1)->find();
            //找到并且是非还款完成态
            if(!empty($res) && !($res['type'] == Constant::PAY_TYPE_WITHDRAWAL && $res['status'] == ConsumeHistoryModel::STATUS_PAY_OK)){
                //错误提示
                $t = $res['type'];
                $s = $res['status'];
                Log::write("用户提现的状态", "customer_id:".$data['customer_id']."; type : ".$t."; status : ".$s, Log::INFO);
                if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && $s == ConsumeHistoryModel::STATUS_WAIT_REVIEWED){
                   return  ['code' => 100, 'msg' => "亲，您的订单处于待审核状态，不可再次申请哦~~"];
                }

                else if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && $s == ConsumeHistoryModel::STATUS_TONDDUN_FAILED){
                   return ['code' => 100, 'msg' => "亲，您的账户在黑名单中，不可再次申请哦~~"];
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL && $s == ConsumeHistoryModel::STATUS_REVIEWED){
                   return ['code' => 100, 'msg' => "亲，您有一笔订单未还款，还款以后再次申请哦~~"];
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL_APPLY && $s == ConsumeHistoryModel::STATUS_REVIEW_FAILED){
                    $now = time();
                    $diff = ($now - $res['add_time']);
                    if($diff < 30 * 24 * 3600) {
                       return ['code' => 100, 'msg' => "亲，您的订单申请未通过，请于30个自然日后再次申请~~"];
                    }
                }
                else if($t== Constant::PAY_TYPE_WITHDRAWAL && $s == ConsumeHistoryModel::STATUS_WAITING_REPAY){
                    return ['code' => 100, 'msg' => "亲，您的订单处于待打款状态~~"];
                }
                else{
                    return ['code' => 100, 'msg' => "抱歉，系统错误，请邮件联系管理员!~~"];
                }
            }
            //保存位置信息
            $this->saveLocationHistory();
            $county_id = D('Position')->getCountyIDByCountyName($data['province'], $data['country']);

            //录入数据，等待审核
            $status = ConsumeHistoryModel::STATUS_WAIT_REVIEWED; //设置审核状态
            $customer['consume_amount'] = $data['apply_amount'];

            //生成零元还款消费记录
            $consumeData = [
                'amount' => $data['apply_amount'],
                'consume_amount' => $data['apply_amount'],
                'discount_first_order' => 0,
                'discount_full_amount' => 0,
                'discount_full_reduce' => 0,
                'type' => Constant::PAY_TYPE_WITHDRAWAL_APPLY,
                'customer_id' => $data['customer_id'],
                'repay_id' => isset($data['repay_id']) ? $data['repay_id'] : 0,
                'merchant_id' => 0,
                'status'=>$status,
                'repayment_time' => 0,
                'add_time' => time(),
                'county_id' => $county_id,
                'laiyuan'=>0
            ];

            $insertId = D('ConsumeHistory')->add($consumeData);
            if (!$insertId) {
               // BusinessException::throwException(Constant::FAILED);
                return ['code'=>'201',''=>'插入ConsumeHistory失败'];
            }
            //记录信审表
            $creditVetting = [
                'customer_id' => $data['customer_id'],
                'consume_id' => $insertId,
                'credit_amount' => 0,
                'status' => CreditVettingModel::STATUS_WAITING_REVIEW,
                'type' => Constant::PAY_TYPE_WITHDRAWAL_APPLY
            ];
            $ins = M('CreditVetting')->add($creditVetting);
            Log::write("[".ACTION_NAME."][记录信审信息][customer_id=".$data['customer_id']."]:".json_encode($creditVetting).",result:".$ins, Log::INFO);

            //同步最新的同盾设备id值
            $new_data_customer = [];
            //$push_id = I('post.push_id', '', 'string');
            $push_id = $data['push_id'];
            //$tdId = I('post.black_box', '', 'string');
            $tdId = $data['black_box'];
            if(!$tdId){
               // BusinessException::throwException(Constant::INVALID_PARAMETER);
                return ['code'=>'201','msg'=>Constant::INVALID_PARAMETER];
            }
            if((0 == strlen($data['customer']['tongdun_device_id']) || $tdId != $data['customer']['tongdun_device_id']) && $tdId != 'h5'){
                $new_data_customer['tongdun_device_id'] = $tdId;
            }
            if($push_id && $push_id != 'h5'){
                $new_data_customer['push_id'] = $push_id;
            }
            if($new_data_customer){
                if(false === M('Customer')->where(['id' => $data['customer_id']])->setField($new_data_customer)){
                    //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    return ['code'=>'201','msg'=>Constant::INTERNAL_ERROR_MYSQL];
                }
                $customer['tongdun_device_id'] = $tdId;
            }

            //稽审
            if($this->AuditOrder($customer)){
                $ids = array('consume_id'=>$insertId, 'credit_id'=>$ins, 'customer_id'=>$data['customer_id']);
                if(!$this->AuditFinish($ids)){
                    //BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    return ['code'=>'201','msg'=>Constant::INTERNAL_ERROR_MYSQL];
                }

                $res2App['is_need_verify'] = 0;
                $res2App['amount'] = Constant::WITHDRAWALS_DEFAULT_AMOUNT;
            }else{
                //执行决策
                $customer['consume_id'] = $insertId;
                $ret = BaseHook::executeHook("MONEY_DECISION_ENGINE_HOOK", $customer, Constant::TONGDUN_CASH_APPLY);
                Log::write("决策引擎:" . json_encode($ret), Log::INFO);
                if (Constant::SUCCESS != $ret['code']) {
                    if(false === D('ConsumeHistory')->where(['id' => $insertId])->setField('status', ConsumeHistoryModel::STATUS_TONDDUN_FAILED)){
                        BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    }
                    $save_data = ['status'=>CreditVettingModel::STATUS_AUTO_REFUSE, 'reason'=>$ret['msg']];
                    if(false === D('CreditVetting')->where(['id'=>$ins])->setField($save_data)){
                        BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
                    }
                    BusinessException::throwException($ret['code'], $ret['msg']);
                }
                $res2App['is_need_verify'] = 1;
                $res2App['consume_id'] = $insertId;
            }
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res2App;
        }catch (BusinessException $e){
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }
    /****** 用户提现 ******/
    public function withdrawalsOrder()
    {
        try{
            //参数校验
            $data = I('post.');
            $data['apply_amount'] = I('post.amount', 0, 'int');
            Log::write("[start][withdrawalsOrder]:开始执行", Log::INFO);
            if (!isset($data['pay_pass_unmatched']) && empty($data['pay_pass_unmatched']) ) {//此处参数为空则校验密码，否则不校验
            	Log::write("pay_pass_unmatched为空则校验密码");
                $customer = $this->orderCommonCheck($data, true);
            }
            // $this->ajaxReturn(['code' => '230', 'msg' => '10.1期间因为银行的原因，找钱花暂停提现，请您10.9提现操作。']);
            $status = ConsumeHistoryModel::STATUS_WAITING_REPAY; //待付款
            //生成零元还款消费记录
            $consumeData = [
                'amount' => $data['apply_amount'],
                'consume_amount' => $data['apply_amount'],
                'discount_first_order' => 0,
                'discount_full_amount' => 0,
                'discount_full_reduce' => 0,
                'type' => Constant::PAY_TYPE_WITHDRAWAL,
                'customer_id' => $data['customer_id'],
                'merchant_id' => 0,
                'status'=>$status,
                'repay_id' => $data['repay_id'],
                'repayment_time' => time(),
                'add_time' => time(),
                'laiyuan'=>0
            ];
            /*判断是否有这条记录*/
            $consume= [
                'type' => Constant::PAY_TYPE_WITHDRAWAL,
                'customer_id' => $data['customer_id'],
                'status'=>$status,
            ];
            $consume_id=D('ConsumeHistory')->where($consume)->find();
            if(!isset($consume_id)){
                $sdasdad =  D('ConsumeHistory')->add($consumeData);
                $insertId =$sdasdad;
            }else{
                $insertId =$consume_id['id'];
            }
            Log::borrow_write("*****************用户提现*****参数：".json_encode(I('post.'))."");
            //开启事务
            M('Finish')->startTrans();
            $res = D('Finish')->WithdrawalOrderFinish($insertId);
            Log::borrow_write("*****************用户提现*****结果：".json_encode($res));
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $res;
        }catch (BusinessException $e){
            M('Finish')->rollback();
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Log::write("[end][orderRealPay][consume_id=".json_encode($ret, JSON_UNESCAPED_UNICODE)."]:执行结束", Log::INFO);

        M('Finish')->commit();
        Response::format($ret);
        //BusinessException::throwException("10.1期间因为银行的原因，找钱花暂停提现，请您10.9提现操作。");
        $this->ajaxReturn($ret);
    }
    /**********************融360|复贷款********************/

    /**********************融360|复贷款********************/
    /*** 提现产品选择 ***/
    public function selWithdrawals()
    {
        try{
            $init = I('post.init', 0, 'int');
            $customerId = I('post.customer_id', 0, 'int');
            if(!$init && !$customerId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }

            $repay_id = 0;
            $reviewed_amount = 0;
            //get 先找到用户在consume_history最近的记录, 对于status=12（审核通过）的则给出客户自己选择的产品了
            if($customerId) {
                $where['customer_id'] = $customerId;
                //审核通过
                $where['status'] = ConsumeHistoryModel::STATUS_CASH_REVIEWED;
                $consumeInfo= M('consumeHistory')->where($where)->order('add_time desc')->field('id,repay_id,status,amount')->find();
                if($consumeInfo){
                    $repay_id = $consumeInfo['repay_id'];
                    $reviewed_amount   = $consumeInfo['amount']; //申请通过的金额
                }
                Log::write("取到的用户信息：", json_encode($consumeInfo)."customerId : ".$customerId.";repay_id : ".$repay_id."; reviewed_amount : ".$reviewed_amount, Log::DEBUG);
            }

            if($init == 0 && $repay_id != 0){
                $cash_conf = M('SysInstallmentPlan')->order('repay_times ASC')->where(['publish' => 1, 'target' => 3, 'id'=>$repay_id,'type'=>1])->select();
                if (!$cash_conf) {
                    BusinessException::throwException(Constant::ERROR_RETURN_DATA);
                }
                Log::write("已选产品conf=".json_encode($cash_conf), Log::DEBUG);
            }else{
                //获取现金贷的分期配置信息
                $cash_conf = M('SysInstallmentPlan')->order('repay_times ASC')->where(['publish' => 1, 'target' => 3,'status'=>1,'type'=>1])->select();
                if (!$cash_conf) {
                    BusinessException::throwException(Constant::ERROR_RETURN_DATA);
                }
                Log::write("未选产品conf=".json_encode($cash_conf), Log::DEBUG);
            }

            $level = 100;
            if($customerId){
                $customer = D('Customer')->has(['id'=>$customerId]);
                $level = $customer['credit_level'];
            }

            //现金贷申请计算
            $max_cash = Constant::MAX_CASH_AMOUNT;
            $def_cash = Constant::MAX_DEF_AMOUNT;
            //$unit = Constant::CASH_UNIT_INIT;
            $unit = Constant::CASH_UNIT_INIT_NEW;

            //现金贷提现, 用户如果balance_cash_amount不为0，则init为0，未登录的时候init为1
            if($init == 0){
                $max_cash = $customer['balance_cash_amount'];
                if ($max_cash > 200000){
                    $max_cash = 200000;
                }
                $unit = Constant::CASH_UNIT;
            }
			//最大额度-暂限定为2000
			/*if ($max_cash > 200000){
                    $max_cash = 200000;
                }*/
            /*if(!$max_cash){//如果最大额度为0--后期用户可同时申请多款产品时需要用到该额度
                $max_cash = 200000;
            }*/
            $max_cash = 900000;
            //拿出当前consume_history的数据，repay_id
            if($repay_id != 0 && $reviewed_amount != 0){
                $amount_data = D('Finish')->WithdrawalsList($cash_conf, $max_cash, $init, $reviewed_amount, $level);
            }else{
                $amount_data = D('Finish')->WithdrawalsList($cash_conf, $max_cash, $init, 0, $level);
            }
            //初始化时-显示所有产品
            if($init==1){
                $amount_data = D('Finish')->WithdrawalsList($cash_conf, $max_cash, $init, 0, $level);

            }
            //初始化时-显示所有产品
            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['max_cash'] = $max_cash;
            $ret['def_cash'] = $def_cash;
            $ret['unit'] = $unit;
            $ret['data'] = $amount_data;
            $json='{
    "code": "0",
    "msg": "成功",
    "max_cash": "900000",
    "def_cash": "50000",
    "unit": "300000",
    "data": [
        {
            "id": "2",
            "repay_unit": "1",
            "repay_times": "9",
            "cash_data": [
                {
                    "withdrawal_amount": "300000",
                    "fee_amount": "42300",
                    "transfer_amount": "219000",
                    "repay_total": "231000"
                },
                {
                    "withdrawal_amount": "600000",
                    "fee_amount": "84600",
                    "transfer_amount": "438000",
                    "repay_total": "462000"
                },
                {
                    "withdrawal_amount": "900000",
                    "fee_amount": "127000",
                    "transfer_amount": "657000",
                    "repay_total": "693000"
                }
            ]
        },
        {
            "id": "3",
            "repay_unit": "1",
            "repay_times": "3",
            "cash_data": [
                {
                    "withdrawal_amount": "300000",
                    "fee_amount": "109000",
                    "transfer_amount": "273000",
                    "repay_total": "279000"
                },
                {
                    "withdrawal_amount": "600000",
                    "fee_amount": "218000",
                    "transfer_amount": "546000",
                    "repay_total": "558000"
                },
                {
                    "withdrawal_amount": "900000",
                    "fee_amount": "327000",
                    "transfer_amount": "819000",
                    "repay_total": "837000"
                }
            ]
        }
    ]
}';
            echo $json;
            Log::borrow_write('--selWithdrawals--返回app数据'.$json);
            die;
        }catch(BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 待审核订单刷新 ******/
    public function withdrawalsRefresh(){
        try{
            $customer_id = I('post.customer_id');
            $consume_id = I('post.consume_id');
            if(!$customer_id || !$consume_id){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            $customer = D('Customer')->has($customer_id);
            //获取用户当前订单的状态
            $res = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
            $data['status'] = $res['status'];
            if($data['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED || $data['status' == ConsumeHistoryModel::STATUS_TONDDUN_FAILED]){
                $data['reason'] = Constant::TIPS_ORDER_FAILED;
            }else if($data['status'] == ConsumeHistoryModel::STATUS_CASH_REVIEWED){
                //$data['amount'] = $customer['balance_cash_amount'];
                //上面那个注释的错了，应该给用户发本次审核通过的钱数，by deron
                $data['amount'] = $res['amount'];
            }

            //写入通知缓存
            CacheRedis::setKey($res['customer_id'], Constant::PAY_TYPE_WITHDRAWAL_APPLY);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = $data;
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 取消订单 ******/
    public function orderCancel(){
        try{
            $customerId = I('post.customer_id');
            $consumeId = I('post.consume_id');
            if(!$customerId || !$consumeId){
                BusinessException::throwException(Constant::INVALID_PARAMETER);
            }
            D('Customer')->has($customerId);
            $res = M('ConsumeHistory')->where(['id' => $consumeId])->find();
            if(!$res){
                BusinessException::throwException(Constant::ORDER_ID_NOT_FOUNT);
            }
            if($res['status'] != ConsumeHistoryModel::STATUS_DOWN_PAYMENT && $res['status'] != ConsumeHistoryModel::STATUS_WAITING_REPAY){
                BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
            }
            //获取用户当前订单的状态
            if(false === M('ConsumeHistory')->where(['id' => $consumeId])->setField('status', ConsumeHistoryModel::STATUS_CANCEL)){
                BusinessException::throwException(Constant::INTERNAL_ERROR_MYSQL);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
        }catch (BusinessException $e){
            $ret = ['code'=>$e->getCode(), 'msg'=>$e->getMessage()];
        }
        Response::format($ret);
        $this->ajaxReturn($ret);
    }

    /****** 稽审 ******/
    public function AuditOrder($customer)
    {
        //检查用户是否为白名单用户
        $white = M('WhiteList')->where(['id_num'=>$customer['id_num'], 'mobile'=>$customer['mobile'], 'status'=>1])->find();
        if($white){
            return true;
        }
        return false;
    }

    /****** 稽审成功 ******/
    public function AuditFinish($ids)
    {
        //更新订单表数据
        $consume_data = ['status'=>ConsumeHistoryModel::STATUS_CASH_AUTO_REVIEWED, 'amount'=>Constant::WITHDRAWALS_DEFAULT_AMOUNT];
        if(false === M('ConsumeHistory')->where(['id'=>$ids['consume_id']])->save($consume_data)){
            return false;
        }

        //更新用户表数据
        $customer_data = ['cash_amount'=>Constant::WITHDRAWALS_DEFAULT_AMOUNT, 'balance_cash_amount'=>Constant::WITHDRAWALS_DEFAULT_AMOUNT];
        if(false === M('Customer')->where(['id' => $ids['customer_id']])->save($customer_data)){
            return false;
        }

        //更新信审表数据
        if(false === M('CreditVetting')->where(
                ['id' => $ids['credit_id'], 'status'=>CreditVettingModel::STATUS_WAITING_REVIEW]
            )->setField('status', CreditVettingModel::STATUS_AUTO_REVIEWED)){
            return false;
        }

        return true;
    }
}
